package flow.controller;

import flow.dto.CompleteRequestDTO;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.*;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/countersign")
public class CountersignController {
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;

    //加签
    //存在问题：加签会把"nrOfInstances"数量加一， 但"nrOfActiveInstances"和"nrOfCompletedInstances"数量并没变化
    @PutMapping("/task")
    public void addCountersignTask(@RequestParam String parentExecutionId) {
        Map map = new HashMap();
        map.put("assignee", "newTask");
        runtimeService.addMultiInstanceExecution("countersigning", parentExecutionId, map);
//        Integer activeCount = taskService.getVariable(taskId, "nrOfActiveInstances");
//        taskService.setVariable(taskId, "nrOfActiveInstances", activeCount);
    }

    //减签
    //存在问题：若被减的签是该会签的最后一个，减签之后无法触发会签监听，流程无法继续
    //存在问题：减签会把"nrOfInstances"数量减一， 但"nrOfActiveInstances"和"nrOfCompletedInstances"数量并没变化
    @DeleteMapping("/task")
    public void deleteCountersignTask(@RequestParam String executionId) {
        List<Task> taskList = taskService.createTaskQuery().taskAssignee("newTask").orderByTaskCreateTime().desc().list();
        if (!CollectionUtils.isEmpty(taskList)) {
            runtimeService.deleteMultiInstanceExecution(taskList.get(0).getExecutionId(), false);
        }
    }

    //启动流程并添加流程变量
    @PostMapping("/start")
    public String startProcess(@RequestBody String username) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("countersign", map);
        return "提交成功.流程Id为：" + processInstance.getId();
    }

    //查询任务及流程变量
    @GetMapping("/task")
    public String listTaskDetail(@RequestParam String assignee) {
        List<Task> taskList = taskService.createTaskQuery()
//                .taskAssignee(assignee)
                .orderByTaskCreateTime()
                .desc()
                .list();
        for (Task task : taskList) {
            Object username = taskService.getVariables(task.getId());
            Map<String, Object> variables = runtimeService.getVariables(task.getExecutionId());
        }
        return taskList.toString();
    }

    //完成任务并添加流程变量
    @PostMapping("/task")
    public void completeTask(@RequestBody CompleteRequestDTO request) {
        Task task = taskService.createTaskQuery()
                .taskId(request.getTaskId())
                .singleResult();
        if (task != null) {
            Map<String, Object> map = new HashMap<>();
            taskService.setVariableLocal(task.getId(), "result", request.isResult());
            taskService.setVariableLocal(task.getId(), "comment", request.getComment());
            map.put("processResult", request.isResult());
            //如果是会签任务，需要记录审核结果数量，便于后面自定义通过规则
            BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
            Process process = bpmnModel.getProcesses().get(0);
            UserTask userTask = (UserTask) process.getFlowElement(task.getTaskDefinitionKey());
            if (userTask.getLoopCharacteristics() != null) {
                String countName = request.isResult() ? "approveCount" : "disapproveCount";
                Integer count = (Integer) taskService.getVariable(task.getId(), countName);
                taskService.setVariable(task.getId(), countName, count == null ? 1 : count + 1);
            }
            taskService.complete(task.getId(), map);
        }
    }

    //查询历史任务及历史流程变量
    @GetMapping("/task/history")
    public void listTaskHistory() {
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();
        for (HistoricTaskInstance task : taskList) {
            Map<String, Object> processVariables = task.getProcessVariables();
            Map<String, Object> taskLocalVariables = task.getTaskLocalVariables();
            List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
//                    .excludeTaskVariables()
                    .processInstanceId(task.getProcessInstanceId())
                    .list();
        }
    }
}
